import { createPortal } from 'react-dom';
import { withRouter } from 'next/router';
import { Component } from 'react';
import { connect } from 'react-redux';
import { CloseCircleOutlined } from '@ant-design/icons';
import Cookies from 'js-cookie';
import { formatTimeString } from '@/utils';
// css
import styles from '@/styles/CommonComponent.module.scss';
// imgs
import topImg from "@/public/imgs/coupon/coupon-1.png";
import leftImg from "@/public/imgs/coupon/coupon-2.png";
import rightImg from "@/public/imgs/coupon/coupon-3.png";
// api
import { sendCoupon, receiveCoupon } from '@/api/coupon';
import { getCartListData } from '@/store/actions/cart';

const basePath = process.env.basePath;

// 优惠券内容
const CouponContent = ({ data }) => {
    return (
        <div className={styles['content']}>
            {
                data.map((item, index) => {
                    const { couponDetailAppDTO = {}, couponType, rebatePrice } = item;
                    const { couponCashRuleDetailAppDTO = {}, couponExperienceRuleDetailAppDTO = {}, couponFullReduceRuleDetailAppDTO = {} } = couponDetailAppDTO;
                    const { validityType, validityDay, endTime } = couponCashRuleDetailAppDTO || couponExperienceRuleDetailAppDTO || couponFullReduceRuleDetailAppDTO || {};
                    return (
                        <div className={styles['item']} key={index}>
                            <div>
                                { couponType == 3 || couponType == 2 ? <p><span>￥</span>{rebatePrice}</p> : '' }
                                { couponType == 2 ? <p className={styles['gray']}>满{item.satisfyPrice}可用</p> : '' }
                                { !(couponType == 3 || couponType == 2) ? '体验券' : '' }
                            </div>
                            <div>
                                <h3>{item.name}</h3>
                                <p className={styles['gray']}>
                                    { validityType == 1 ? `有效期至${formatTimeString(endTime)}内有效` : `领取${validityDay || 0}天内有效` }
                                </p>
                            </div>
                        </div>
                    )
                })
            }
        </div>
    )
}

// 优惠券弹框Component
class CouponPopOver extends Component{
    render() {
        const { coupons, btnTxt, disabled } = this.state;
        const { router } = this.props;
        if(coupons.length){
            return createPortal(
                <div className={styles['coupon-popover']}>
                    <div className={styles['wrapper']}>
                        <CloseCircleOutlined onClick={() => { this.closeCouponFn() }} />
                        <img className={styles['top']} src={basePath + topImg.src} alt="" />
                        <img className={styles['left']} src={basePath + leftImg.src} alt="" />
                        <img className={styles['right']} src={basePath + rightImg.src} alt="" />
                        <CouponContent data={coupons} />
                        <div className={styles['operation']}>
                            <button className={styles['receive-btn']} disabled={disabled} onClick={() => { this.receiveCouponFn() }}>{btnTxt}</button>
                            <button className={styles['more-btn']} onClick={() => { router.push('/personal/coupon') }}>更多优惠</button>
                        </div>
                    </div>
                </div>,
                document.querySelector('body')
            )
        }
        return <></>
    }
    state = {
        allCoupons: [],
        coupons: [],
        btnTxt: '一键领取',
        disabled: false
    }
    componentDidMount (){
        // 领取优惠券
        sendCoupon().then(res => {
            const { code, data } = res;
            if(code === 0 && data && data.length){
                const _data = data.slice(0,2).map(item => {
                  const dto = item.couponDetailAppDTO,
                    dto_3 = dto.couponCashRuleDetailAppDTO,
                    dto_2 = dto.couponFullReduceRuleDetailAppDTO,
                    dto_1 = dto.couponExperienceRuleDetailAppDTO;
                  const name = dto.name,
                    couponType = dto.couponType,
                    rebatePrice = dto_2?.rebatePrice || dto_3?.rebatePrice,
                    satisfyPrice = dto_2?.satisfyPrice || "",
                    endTime = dto_2?.endTime || "",
                    validityDay = dto_1?.validityDay || dto_3?.validityDay;
                  return {
                    ...item,
                    name,
                    couponType,
                    rebatePrice,
                    satisfyPrice,
                    endTime,
                    validityDay,
                  }
                });
                this.setState({
                    coupons: [..._data],
                    allCoupons: [...data]
                })
            }
        })
    }
    // 关闭弹出
    closeCouponFn = () => {
        this.setState({
            coupons: []
        })
    }
    // 领取优惠券
    receiveCouponFn = () => {
        const { router, _getCartListData } = this.props;
        // 未登录，跳转到登录页面
        if (!Cookies.get("token")) {
            router.push("/login");
            return false
        }
        const { allCoupons } = this.state;
        const ids = allCoupons.map(item => item.id);
        this.setState({
            btnTxt: '领取中...',
            disabled: true
        });
        receiveCoupon({
            ids: ids
        }).then(res => {
            const { code } = res;
            if (code == 0) {
                router.push("/personal/coupon/?state=2");
                _getCartListData();
            }
            this.setState({
                btnTxt: '一键领取',
                disabled: false
            })
        })
    }
}

const mapStateToProps = (state) => {
    return {
        cart: state.cart
    }
}
const mapDispatchToProps = (dispatch) => {
    return {
        _getCartListData: (v) => dispatch(getCartListData(v))
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(CouponPopOver))